package edu.rpi.bt.client;

import java.util.List;

import com.apress.progwt.client.college.ServiceCache;
import com.apress.progwt.client.domain.User;
import com.apress.progwt.client.domain.commands.SiteCommand;
import com.apress.progwt.client.rpc.EZCallback;
import com.apress.progwt.client.rpc.StdAsyncCallback;
import com.gwtext.client.core.EventObject;
import com.gwtext.client.core.Position;
import com.gwtext.client.widgets.Button;
import com.gwtext.client.widgets.MessageBox;
import com.gwtext.client.widgets.Panel;
import com.gwtext.client.widgets.Window;
import com.gwtext.client.widgets.event.ButtonListenerAdapter;
import com.gwtext.client.widgets.form.Field;
import com.gwtext.client.widgets.form.FormPanel;
import com.gwtext.client.widgets.form.TextArea;
import com.gwtext.client.widgets.form.TextField;

import edu.rpi.bt.client.domain.Destination;
import edu.rpi.bt.client.domain.commands.SaveDestinationCommand;

public class ManageLocationWindow extends Window{
    private Destination destination = new Destination();
    final private Destination trip;
    
    private ServiceCache serviceCache;
    private User thisUser;
    private ManageLocationWindow thisWindow = this;
    private ManageTripWindow tripWindow;
    private List<Destination> destinations;

    
    public AddressStore addressStore;
    
    ManageLocationWindow(Destination trip, ServiceCache servCache){
        this.trip = trip;
        this.setTitle("Add This Location");  
        init(servCache);
    }
    
    ManageLocationWindow(Destination trip, long destinationId, ServiceCache servCache){
        this.trip = trip;
        this.setTitle("Edit This Location");  
        init(servCache);
    }
    
    private void init(ServiceCache servCache){
        this.serviceCache = servCache;
        this.setClosable(true);
        this.setDraggable(true);
        this.setWidth(570);  
        this.setHeight(330);  
        this.setPlain(true);  
        this.setModal(true);

        serviceCache
        .getCurrentUser(new StdAsyncCallback<User>("Get User") {

            public void onSuccess(User result) {
                super.onSuccess(result);
                if (result == null) {
                 
                } else {
                   
                    load(result);
                }
            }

            public void onFailure(Throwable caught) {
                super.onFailure(caught);
              
            }
        });
        
        FormPanel formPanel = buildFormPanel();
        
        this.add(new Panel("", "Enter the name and description of the location shown on the map.") );
        this.add( formPanel );       
        
    }
    
    
    
    private FormPanel buildFormPanel(){
 //       if getDestinations()
        //System.out.println("Num of destinations " + getDestinations().size());
        final FormPanel formPanel = new FormPanel();  
        formPanel.setFrame(true);  
       // formPanel.setWidth(390);

        formPanel.setLabelWidth(90);
        formPanel.setLabelAlign(Position.LEFT);
       // formPanel.setUrl("save-form.php");  
        
        TextField name = new TextField("Location Name", "name");
        name.setWidth(425);
        name.setAllowBlank(false);  
        formPanel.add( name );  
        
        TextArea description = new TextArea("Description", "description");
        description.setWidth(425);
        description.setHeight(200);
        formPanel.add(description);  

         //icon button  
         Button saveButton = new Button("Save", new ButtonListenerAdapter() {  
             public void onClick(Button button, EventObject e) {
                 //ashoo: This is to check who the user is, to be commented
                // MessageBox.alert("user is " + thisUser.getNickname());
               //ashoo: This is to how many destinations=trip set, to be commented
               //  MessageBox.alert("Num of destinations " + getDestinations().size());
                 
                 Field[] fields = formPanel.getFields();
                 for( int i=0; i < fields.length; i++ ){
                     if( fields[i].getName() == "name"){
                         destination.setName( fields[i].getValueAsString() );
                     } else if( fields[i].getName() == "description"){
                         destination.setDescription( fields[i].getValueAsString() );
                     }
                 }
                 
                 if( destination.getName() == null ){
                     MessageBox.alert("Error: You must enter a name for this location.");
                     return;
                 }
                 
                 destination.setAddress( addressStore.address );
                 destination.setLatitude( addressStore.latLon.getLat() );
                 destination.setLongitude( addressStore.latLon.getLon() );
     //            MessageBox.alert("Address: " + destination.getAddress() + "<br>Name: " + destination.getName() + "<br>Descrip: " + destination.getDescription());                 
                 
                 //destination.setParent( trip );
                 
                 // MessageBox.alert("Address: " + destination.getAddress() + "<br>Name: " + destination.getName() + "<br>Descrip: " + destination.getDescription() );                 
                 // Some call back here
             /*   
                 serviceCache.getCurrentUser(new EZCallback<User>() {

            public void onFailure(Throwable caught) {
                Log.error("Banana...setmeupFailure " + caught);
                System.out.println("Banana...setmeupFailure " + caught);
            }

            public void onSuccess(User result) {
                System.out.println("Banana...setmeup");
               load(result);

            }
        });
             
             */
                 
              if(trip !=null){
                 destination.setParent(trip);
              }
                 destination.setUser(thisUser);
       //          MessageBox.alert("Address: " + destination.getAddress() + "<br>Name: " + destination.getName() + "<br>Descrip: " + destination.getDescription() + "<br>User: " + destination.getUser().getNickname() );                 
                
                 SaveDestinationCommand comm = new SaveDestinationCommand(destination);
                 //   MessageBox.alert("command");
                    serviceCache.executeCommand(comm, new EZCallback<SiteCommand>() {
                    //    MessageBox.alert("execute"); 
                        public void onSuccess(SiteCommand success) {
                           // MessageBox.alert("execute"); 
                            SaveDestinationCommand rtn = (SaveDestinationCommand) success;
                            //MessageBox.alert("done saving"); 
                            destination.setId(rtn.getSavedDestinationID());
                            
                            //MessageBox.alert("Destination id " + destination.getId()); 
                            
                            tripWindow.reinitTrip();
                            thisWindow.close();
                        //    System.out.println("Destination id " + rtn.getSavedDestinationID() );
                        //    MessageBox.alert("Destination id " + destination.getId()); 
                        }
                    });
             }  
         });  
                  
         formPanel.add(saveButton);  
         
        return formPanel;
    }   
    
    
    public void load(User user){
        this.thisUser=user;
       
 //       this.destinations=(List<Destination>) user.getDestinations();
        
    }
    public void load(List<Destination> dests){
        //MessageBox.alert("adding destination"); 
        this.destinations=dests;
        
    }
    
    public  List<Destination> getDestinations(){
     //   System.out.println("inside getdests");
        //MessageBox.alert("inside get destination"); 
        return this.destinations;
    }
    
    public void setTripWindow( ManageTripWindow mtw ){
        this.tripWindow = mtw;
    }
}
